from django.shortcuts import render_to_response
from django.template import RequestContext
from ysna.auth.models import AbstractUser, Thread, MSG, ThreadNotification
import datetime

def checkThreads(request, thread_id):
    return viewThreads(request, thread_id, False)

def viewThreads(request, thread_id, newMSG, threads_len=10):
    from ysna.myprofile.views import getUser
    abstract_user = AbstractUser.objects.get(user=request.user)
    threads = abstract_user.thread_set.all().order_by('-date_started')
    friends = getUsernamesNids(abstract_user.friends.all())
    print friends
    if thread_id and thread_id != '0':
        thread = Thread.objects.get(pk=thread_id)
        messages = MSG.objects.filter(thread=thread)
        subject = thread.subject 
        current_thread = Thread.objects.get(pk=thread_id)
        
        # if a thread is being checked, then change the notifications for that thread to zero
        thread_notification = ThreadNotification.objects.get(thread=thread, abstract_user=abstract_user)
        thread_notification.notifications = 0
        thread_notification.save()
        
    else:
        messages, subject, current_thread = None, None, None
    
    if len(threads) > threads_len: 
        threads = threads[0:threads_len]
        more_threads_available = True
    else:
        more_threads_available = False
        
    threads_and_notifications = []
    for thread in threads:
        threads_and_notifications.append([thread, ThreadNotification.objects.get(thread=thread, abstract_user=abstract_user).notifications])
    
    # change the notifications to zero since threads will be viewed now
    abstract_user.messages_notification = 0
    abstract_user.save()
    
    return render_to_response('messaging/allThreads.html', {'loggedinUser':getUser(request.user, False),
                                                            'threads':threads,
                                                            'threads_and_notifications':threads_and_notifications, 
                                                            'messages':messages, 
                                                            'subject':subject,  
                                                            'profileOwner':True,
                                                            'friends':friends, 
                                                            'current_thread':current_thread, 
                                                            'currentUser':getUser(request.user, abstract=False),
                                                            'thread_id':thread_id,
                                                            'more_threads_available':more_threads_available}
                              , context_instance=RequestContext(request))

def respondToThread(request, thread_id):
    # Check if there is data being sent, to avoid error page duo to url manipulation
    if request.method != 'POST':
        return viewThreads(request, None, True)
    
    content = request.POST['content']
    thread = Thread.objects.get(pk=thread_id)
    sender = AbstractUser.objects.get(user=request.user)
    date_sent = datetime.datetime.now()
    
    # Check if user is refreshing the page after sending the msg in the last minute
    msgs = MSG.objects.filter(thread=thread, content=content, sender=sender)
    for msg in msgs:
        if msg.date_sent > date_sent - datetime.timedelta(minutes=1):
            return viewThreads(request, msg.thread.id, True)
        
    message = MSG(thread=thread, content=content, sender=sender, date_sent=date_sent)
    message.save()
    
    for receiver in thread.receivers.all():
        if receiver != sender:
            receiver.messages_notification += 1
            thread_notification = ThreadNotification.objects.get(abstract_user=receiver, thread=thread)
            thread_notification.notifications += 1
            thread_notification.save()
            receiver.save()
    return checkThreads(request, thread_id)

def startThread(request):
    # Check if there is data being sent, to avoid error page duo to url manipulation
    if request.method != 'POST':
        return viewThreads(request, None, True)
    
    subject = request.POST['subject']
    receivers = request.POST['as_values_receivers']
    content = request.POST['content']
    sender = AbstractUser.objects.get(user=request.user)
    date_sent = datetime.datetime.now()
    
    # Check if user is refreshing the page after sending the msg in the last minute
    msgs = MSG.objects.filter(content=content, sender=sender)
    for msg in msgs:
        if msg.date_sent > date_sent - datetime.timedelta(minutes=1):
            return viewThreads(request, msg.thread.id, True)
    
    if not subject: subject = 'No subject'
    
    thread = Thread(category='msg', subject=subject, date_started=datetime.datetime.now(), admin=False)
    thread.save()
    
    thread.receivers.add(AbstractUser.objects.get(user=request.user))
    ThreadNotification(thread=thread, abstract_user=AbstractUser.objects.get(user=request.user), notifications=0).save()
    
    for receiver in receivers.split(','):
        if receiver != '':
            current = AbstractUser.objects.get(pk=int(receiver))
            thread.receivers.add(current)
            current.messages_notification += 1
            ThreadNotification(thread=thread, abstract_user=current, notifications=1).save()
            current.save()
    
    thread.save()
    
    
    
    
    date_sent = datetime.datetime.now()
    sender = AbstractUser.objects.get(user=request.user)
    message = MSG(thread=thread, content=content, sender=sender, date_sent=date_sent)
    message.save()
    
    return checkThreads(request, thread.id)

def sendNewMessage(request):
    return viewThreads(request, 0, True)

def getUsernamesNids(abstract_users):
    result = '['
    for abstract_user in abstract_users:
        result += '{value: ' + '"' + str(abstract_user.id) + '", name: "' + abstract_user.user.username + '"},'
    if result[0:len(result)-1]:
        return result[0:len(result)-1] + ']'
    else:
        return None

'''
author: Nader Alexan
date: 22.04.12
desc: Allow the user to remove himself from a thread
'''
def removeReceiver(request, thread_id):
    try:
        thread = Thread.objects.get(pk=thread_id)
        abstract_user = AbstractUser.objects.get(user=request.user)
        thread.receivers.remove(abstract_user)
        ThreadNotification.objects.get(thread=thread, abstract_user=abstract_user).delete()
        if thread.receivers.all():
            thread.save()
        else:
            thread.delete()
    except: pass
    return viewThreads(request, None, True)

def viewMoreThreads(request, threads_len, thread_id):
    return viewThreads(request, int(thread_id), False, threads_len=int(threads_len)+10)
    